package com.sctvcloud.zhaohua_sd.ui.activities;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Pair;
import android.view.View;
import android.widget.LinearLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.ruihang.generalibrary.db.DBUtils;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.DensityUtil;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.zhaohua_sd.R;
import com.sctvcloud.zhaohua_sd.base.BaseActivity;
import com.sctvcloud.zhaohua_sd.beans.FHistory;
import com.sctvcloud.zhaohua_sd.beans.NewsItem;
import com.sctvcloud.zhaohua_sd.ui.adapter.HistoriesAdapter;
import com.sctvcloud.zhaohua_sd.ui.util.RBaseItemDecoration;
import com.sctvcloud.zhaohua_sd.ui.utils.SkipUtil;
import com.sctvcloud.zhaohua_sd.ui.utils.TitleUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 历史记录
 */
public class HistoriesActivity extends BaseActivity implements View.OnClickListener,
        CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener {
    @BindView(R.id.title_top_edit)
    protected CustomFontTextView mBtnClear;
    @BindView(R.id.can_content_view)
    protected RecyclerView mRecyclerView;
    @BindView(R.id.histories_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.my_history_no)
    protected LinearLayout no_history;
    private HistoriesAdapter mAdapter;
    private List<FHistory> list = null;
    private int currentNum;
    private int size;
    private int limit_number = 20;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this).useAndSetTxTitle("历史记录");
        initView();
    }
    @Override
    protected void initInject() {
        setContentView(R.layout.activity_histories);
        ButterKnife.bind(this);
    }
    private void initView() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        mBtnClear.setText(getString(R.string.setting_clear));
        mBtnClear.setOnClickListener(this);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new RBaseItemDecoration(DensityUtil.dip2px(this, 1),
                ContextCompat.getColor(this, R.color.colorItemListDivider)));
        try {
            List<FHistory> all = DBUtils.getInstance().findAll(FHistory.class);
            size = all.size();
            if (size == 0) {
                mBtnClear.setVisibility(View.GONE);
            } else {
                mBtnClear.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        refreshLayout.autoRefresh();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_top_edit:
                clearData();
                break;
        }
    }

    /**
     * 初始化显示
     * @param list
     */
    private void getHistories(List<FHistory> list) {
        if (ListUtils.isListValued(list)) {
            if (currentNum == 0) {
                if (mAdapter == null) {
                    mAdapter = new HistoriesAdapter(this, list).setItemInternalClick(historiesItemClick);
                    mRecyclerView.setAdapter(mAdapter);
                } else {
                    mAdapter.setData(list);
                }
            } else {
                int pos = mAdapter.getItemCount();
                mAdapter.addDatas(list);
                if (pos > 0) {
                    mAdapter.notifyItemChanged(pos - 1);
                }
            }
        } else {
            return;
        }
    }

    /**
     * 清除历史记录的数据（本地）
     */
    private void clearData() {
        try {
            DBUtils.getInstance().deleteAll(FHistory.class);
        } catch (Exception e) {
        }
        if (mAdapter != null) {
            mAdapter.clean();
        }
        mBtnClear.setVisibility(View.GONE);
        onRefresh();
    }

    /**
     * 点击历史记录中的数据  响应
     */
    private OnItemInternalClick historiesItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            FHistory history = null;
            if (view == null) {
                history = (FHistory) itemView.getTag(R.id.adapter_item_data_key);
            } else {
                history = (FHistory) itemView.getTag(R.id.adapter_item_data_key);
            }
            if (history != null) {
                NewsItem newsItem = new NewsItem();
                newsItem.setNewsId(history.getNewsId());
                newsItem.setFocusNews(history.isFocusNews());
                newsItem.setNewsImage(history.getNewsImage());
                newsItem.setNewsMediaLength(history.getNewsMediaLength());
                newsItem.setNewsTitle(history.getNewsTitle());
                newsItem.setNewsType(history.getNewsType());
                newsItem.setNewsUrl(history.getNewsUrl());
                newsItem.setPubTime(history.getPubTime());
                newsItem.setSkipType(history.getSkipType());
                newsItem.setLable(history.getLable());
                SkipUtil.skipWithNewsItem(HistoriesActivity.this, newsItem,new HashMap<String, String>());
            } else {
                toast("数据错误");
            }

        }
    };

    @Override
    public void onLoadMore() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.loadMoreComplete();
        } else {
            currentNum = currentNum + limit_number;
            if (currentNum <= size) {
                getHistoryList(currentNum);
            }
        }
    }

    @Override
    public void onRefresh() {
        currentNum = 0;
        getHistoryList(currentNum);

    }


    /**
     * 从本地数据库中获取 历史记录数据
     * @param number
     */
    private void getHistoryList(final int number) {
        DBUtils.getInstance().findPageListByColumnAsycn(FHistory.class,
                null, null, null, "historyTime", number, limit_number, true, new DBUtils.DBListAsyncCallBack<FHistory>() {
                    @Override
                    public void findListInDB(List<FHistory> result) {
                        currentNum = number;
                        if (ListUtils.isListValued(result)) {
                            no_history.setVisibility(View.GONE);
                            refreshLayout.setVisibility(View.VISIBLE);
                            refreshLayout.setLoadMoreEnabled(currentNum + limit_number < size);
                            getHistories(result);
                        } else {
                            if (currentNum == 0) {
                                no_history.setVisibility(View.VISIBLE);
                                refreshLayout.setVisibility(View.GONE);
                            }
                            return;
                        }

                    }

                    @Override
                    public void onEnd(String msg) {
                        super.onEnd(msg);
                        if (refreshLayout.isRefreshing()) {
                            refreshLayout.refreshComplete();
                        }
                        if (refreshLayout.isLoading()) {
                            refreshLayout.loadMoreComplete();
                        }
                    }
                });
    }
}
